import json
from config import h3yun_config, file_url_config
from config import excel_config
from h3yun.api import business_data_api
from config.api_params.bizObject_params import set_CreateBizObjects_params
import pandas as pd
from logs.set_logfile import logger
from mate.config import params
from utils.clean_utils import is_empty


# 上传到日更流向表当中
def upload_day_sales_data(file_url=file_url_config.download_one_day_total_excel_file_url):
    df = pd.read_excel(file_url,
                       dtype={'产品编码(配送商的)': str, '产品编码(公司内部的)': str, '客户编码(配送商的)': str, '医院编码(公司内部的)': str})

    df = df.fillna('')

    sales_list = []
    sales_exception_list = []
    column_name = excel_config.column_name
    for i in range(len(df['ID'])):
        sales_dict = {
            'F0000009': str(df[column_name['ID']][i]),
            'F0000001': str(df[column_name['CKSJ']][i]),
            'F0000002': str(df[column_name['PSS']][i]),
            'F0000018': str(df[column_name['CPMC_PSS']][i]),
            'F0000003': str(df[column_name['CPMC_GSNB']][i]),
            'F0000013': str(df[column_name['CPBM_PSS']][i]),
            'F0000014': str(df[column_name['CPBM_GSNB']][i]),
            'F0000004': str(df[column_name['SCCJ']][i]),
            'F0000019': str(df[column_name['KHMC_PSS']][i]),
            'F0000005': str(df[column_name['YYMC_GSNB']][i]),
            'F0000015': str(df[column_name['KHBM']][i]),
            'F0000016': str(df[column_name['YYBM']][i]),
            'F0000006': str(df[column_name['SL']][i]),
            'F0000007': str(df[column_name['DJ']][i]),
            'F0000011': handle_multiply_data(df[column_name['SL']][i], df[column_name['DJ']][i]),
            'F0000008': str(df[column_name['PCXX']][i]),
            'F0000020': str(df[column_name['LHXX']][i]),
            'F0000010': str(df[column_name['SJLY']][i]),
            'F0000017': str(df[column_name['YC']][i])
        }
        if is_empty(str(df[column_name['YC']][i])):
            sales_list.append(json.dumps(sales_dict, ensure_ascii=False))
        else:
            sales_exception_list.append(json.dumps(sales_dict, ensure_ascii=False))

    # 没有错的数据
    params1 = set_CreateBizObjects_params(schema_code=h3yun_config.daily_sales_schemaCode, data=sales_list)
    response1 = business_data_api.createBizObjects_api(params1)
    logger.info(response1.json())

    # 有错的数据
    params2 = set_CreateBizObjects_params(schema_code=h3yun_config.daily_sales_exception_schemaCode, data=sales_exception_list)
    response2 = business_data_api.createBizObjects_api(params2)
    logger.info(response2.json())


# 上传到季度销售表中
def upload_season_sales_volume_data(file_url=params.summary_excel_file_path):
    df = pd.read_excel(file_url, dtype={'产品内部编码': str, '产品批次': str})
    df = df.fillna('')
    season_sales_volume_list = []
    for i in range(len(df['ID'])):
        season_sales_volume_dict = {}
        for key, value in excel_config.season_sales_volume_column_name.items():
            season_sales_volume_dict[excel_config.season_sales_volume_column_h3yun_code[key]] = str(df[value][i])
        season_sales_volume_list.append(json.dumps(season_sales_volume_dict, ensure_ascii=False))
    params = set_CreateBizObjects_params(schema_code=h3yun_config.season_sales_volume_schemaCode, data=season_sales_volume_list)
    response = business_data_api.createBizObjects_api(params)
    logger.info(response.json())


# 上传到专员季度销售达标情况表中
def upload_season_specialist_data(file_url=params.specialist_excel_file_path):
    df = pd.read_excel(file_url)
    df = df.fillna('')
    season_specialist_list = []
    for i in range(len(df['季度'])):
        special_sales_dict = {}
        for key, value in excel_config.specialist_column_name.items():
            special_sales_dict[excel_config.specialist_column_code[key]] = str(df[value][i])
        season_specialist_list.append(json.dumps(special_sales_dict, ensure_ascii=False))
    params = set_CreateBizObjects_params(schema_code=h3yun_config.season_specialist_schemaCode,
                                         data=season_specialist_list)
    response = business_data_api.createBizObjects_api(params)
    logger.info(response.json())


# 上传到经理季度销售达标情况中
def upload_season_manager_data(file_url=params.manager_excel_file_path):
    df = pd.read_excel(file_url)
    df = df.fillna('')
    season_manager_list = []
    for i in range(len(df['季度'])):
        manager_sales_dict = {}
        for key, value in excel_config.manager_column_name.items():
            manager_sales_dict[excel_config.manager_column_code[key]] = str(df[value][i])
        season_manager_list.append(json.dumps(manager_sales_dict, ensure_ascii=False))
    params = set_CreateBizObjects_params(schema_code=h3yun_config.season_manage_schemaCode,
                                         data=season_manager_list)
    response = business_data_api.createBizObjects_api(params)
    logger.info(response.json())


def handle_multiply_data(a, b):
    try:
        a_float = float(a) if a not in [None, '', 'null'] else 0.0
    except ValueError:
        a_float = 0.0

    try:
        b_float = float(b) if b not in [None, '', 'null'] else 0.0
    except ValueError:
        b_float = 0.0

    return a_float * b_float


if __name__ == '__main__':
   upload_day_sales_data()
  #  upload_season_sales_volume_data()

